package com.srwl.mytx.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.domain.Comment;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.CommentService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CommentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "CommentAdapter";
    private Context context;
    private List<Comment> commentList;
    private CommentClickListener commentClickListener;
    private boolean forbiddenItemClick;
    private boolean showFooter;
    private boolean noMoreData;

    public CommentAdapter(Context context, List<Comment> commentList) {
        this.context = context;
        this.commentList = commentList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case Constant.COMMENT_TYPE_NORMAL:
                return new CommentViewHolder(LayoutInflater.from(context).inflate(R.layout.tx_comment_item, parent, false));

            case Constant.COMMENT_TYPE_CHILD:
                return new ChildCommentViewHolder(LayoutInflater.from(context).inflate(R.layout.tx_child_comment_item_1, parent, false));

            case Constant.COMMENT_TYPE_FOOTER:
                return new FooterViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_list_footer, parent, false));
            default:
                return new ChildCommentViewHolder(LayoutInflater.from(context).inflate(R.layout.tx_child_comment_item_1, parent, false));
        }

    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (commentClickListener != null) {
                    commentClickListener.commentItemLongClick(commentList.get(position));

                    return true;
                } else {
                    return false;
                }

            }
        });
        if (holder instanceof CommentViewHolder) {
            final CommentViewHolder commentViewHolder = (CommentViewHolder) holder;
            final Comment comment = commentList.get(position);
            commentViewHolder.tv_nick.setText(comment.getFromNick());
            commentViewHolder.tv_content.setText(comment.getContent());

            setPraiseView(commentViewHolder, comment);
            commentViewHolder.tv_commentPraiseSize.setText(Utils.numberFormat(comment.getPraiseSize()));
            if (comment.getChildSize() != 0) {
                commentViewHolder.rl_showMoreChildComment.setVisibility(View.VISIBLE);
                commentViewHolder.tv_childCommentSize.setText(comment.getChildSize() + "");
                //如果此父评论是转开子评论的状态，就显示绿色朝上的箭头，否则显示朝下黑色箭头
                if (comment.isDisplayChildComments()) {
                    commentViewHolder.iv_arrow.setImageResource(R.drawable.tx_arrow_down_blue);
                    commentViewHolder.iv_arrow.setRotation(-180);
                } else {
                    commentViewHolder.iv_arrow.setImageResource(R.drawable.tx_arrow_down);
                    commentViewHolder.iv_arrow.setRotation(0);

                }

            } else {
                commentViewHolder.rl_showMoreChildComment.setVisibility(View.GONE);
            }
//            RequestOptions options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).dontAnimate();
//            Glide.with(context).load(comment.getFromAvatar()).apply(options).into(commentViewHolder.iv_avatar);
            GlideLoadUtils.glideLoad(context, comment.getFromAvatar(), commentViewHolder.iv_avatar);

            commentViewHolder.iv_avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (commentClickListener != null) {
                        User targetUser = getTargetUser(comment);
                        commentClickListener.avatarClick(targetUser);
                    }
                }
            });
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (forbiddenItemClick) {
                        return;
                    }
                    if (commentClickListener != null) {
                        commentClickListener.commentItemClick(comment, holder.getLayoutPosition());
                    }
                }
            });
            commentViewHolder.rl_commentPraise.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //((CommentViewHolder) holder).tv_commentPraiseSize.setText(likeSize+"");
                    //因为点赞并不是很重要，所以在点赞之后，直接根据是否点过赞，做出相应的页面相应，并不需要等待服务端响应
                    if (commentClickListener != null) {
                        if (comment.isHadPraise()) {
                            comment.setHadPraise(false);
                            comment.setPraiseSize(comment.getPraiseSize() - 1);

                            commentClickListener.removeCommentPraise(comment, position);
                        } else {
                            comment.setHadPraise(true);
                            comment.setPraiseSize(comment.getPraiseSize() + 1);
                            commentClickListener.addCommentPraise(comment, position);
                        }
                        setPraiseView(commentViewHolder, comment);
                    }
                }
            });

            commentViewHolder.rl_showMoreChildComment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //折叠评论
                    if (comment.isDisplayChildComments()) {
                        comment.setDisplayChildComments(false);
                        commentList.removeAll(comment.getChildCommentList());
                        commentViewHolder.tv_moreReply.setText("查看回复：");
                        ViewAnimator.animate(commentViewHolder.iv_arrow).rotation(0).duration(300).onStop(new AnimationListener.Stop() {
                            @Override
                            public void onStop() {
                                commentViewHolder.iv_arrow.setImageResource(R.drawable.tx_arrow_down);

                            }
                        }).start();
                        // commentViewHolder.iv_arrow.setImageResource(R.drawable.tx_more_arrow);

                        // notifyDataSetChanged();
                        notifyItemRangeRemoved(position + 1, comment.getChildCommentList().size());
                        notifyItemRangeChanged(position + 1, commentList.size() - 2 - position);
                        return;
                    }
                    //如果含有子评论的数据，就地展示，如果没有，就去服务端下载数据
                    if (comment.getChildCommentList() != null && comment.getChildCommentList().size() != 0) {
                        displayChildComment(commentViewHolder, position, comment);
                    } else {
                        loadChildComment(commentViewHolder, comment, position);
//                        if (commentClickListener != null) {
//                            commentClickListener.getChildComment(commentViewHolder, comment, position);
//                        }
                    }
                }
            });
        } else if (holder instanceof ChildCommentViewHolder) {
            final ChildCommentViewHolder childCommentViewHolder = (ChildCommentViewHolder) holder;
            childCommentViewHolder.childComment = commentList.get(position);
            final Comment childComment = commentList.get(position);
            childCommentViewHolder.tv_nick.setText(childComment.getFromNick());
            childCommentViewHolder.tv_content.setText(childComment.getContent());
            // Glide.with(context).load(childComment.getFromAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).dontAnimate().into(childCommentViewHolder.iv_avatar);
            GlideLoadUtils.glideLoad(context, childComment.getFromAvatar(), childCommentViewHolder.iv_avatar);
            //2表示是子评论的回复
            if (childComment.getType() == 2) {
                childCommentViewHolder.ll_replay.setVisibility(View.VISIBLE);
                childCommentViewHolder.tv_replayNick.setText(childComment.getToNick());
            }
            //判断是不是子评论的最后一个，如果是，显示“加载更多评论”
//            if (position==childComment.getParentCommentPosition()+childComment.getParentComment().getChildSize()){
//
//            }

            if (childComment.getParentComment() != null && childComment.getParentComment().getChildCommentList() != null && childComment.getParentComment().getChildCommentList().size() != 0 &&
                    childComment == childComment.getParentComment().getChildCommentList().get(childComment.getParentComment().getChildCommentList().size() - 1)) {
                //如果是最后一个，让高度充满item的竖线隐藏
                childCommentViewHolder.line_2.setVisibility(View.GONE);
                //如果还有更多子评论，显示 加载更多的按键，并设置监听
                if (childComment.getParentComment().isHaveMoreChildComment()) {
                    childCommentViewHolder.ll_loadMore.setVisibility(View.VISIBLE);
                    childCommentViewHolder.ll_loadMore.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            if (commentClickListener != null) {
//                                commentClickListener.getChildComment(null, childComment.getParentComment(), commentList.indexOf(childComment.getParentComment()));
//                            }
                            loadChildComment(null, childComment.getParentComment(), commentList.indexOf(childComment.getParentComment()));
                        }
                    });
                } else {
                    childCommentViewHolder.ll_loadMore.setVisibility(View.GONE);
                }
            } else {
                childCommentViewHolder.line_2.setVisibility(View.VISIBLE);
                //不加下面这句，多加载几次后，原本不是最后位置的item也会显示出“加载更多”按键，我猜是因为曾经这个位置 被尾Item 占用过，item复用造成的
                childCommentViewHolder.ll_loadMore.setVisibility(View.GONE);
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (forbiddenItemClick) {
                        return;
                    }

                    if (commentClickListener != null) {
                        User replyUser = new User(childComment.getFromUid());
                        replyUser.setUsername(childComment.getFromNick());
                        replyUser.setAvatar(childComment.getFromAvatar());
                        commentClickListener.childCommentItemClick(childComment.getParentComment(), holder.getLayoutPosition(), replyUser);
                    }
                }
            });

        } else {
            FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
            if (noMoreData) {
                footerViewHolder.progressBar.setVisibility(View.GONE);
                footerViewHolder.tvLoadingMsg.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setPraiseView(CommentViewHolder commentViewHolder, Comment comment) {
        if (comment.isHadPraise()) {
            commentViewHolder.iv_commentPraise.setBackgroundResource(R.drawable.tx_good_blue);
        } else {
            commentViewHolder.iv_commentPraise.setBackgroundResource(R.drawable.tx_good_gray);
        }
        if (comment.getPraiseSize() != 0) {
            commentViewHolder.tv_commentPraiseSize.setText(Utils.numberFormat(comment.getPraiseSize()));
        } else {
            commentViewHolder.tv_commentPraiseSize.setText("");


        }
    }

    @NonNull
    private User getTargetUser(Comment comment) {
        User targetUser = new User(comment.getFromUid());
        targetUser.setAvatar(comment.getFromAvatar());
        targetUser.setNick(comment.getFromNick());
        return targetUser;
    }

    @Override
    public int getItemViewType(int position) {
        if (showFooter && position == commentList.size()) {
            return Constant.COMMENT_TYPE_FOOTER;
        } else {
            return commentList.get(position).getType();
        }
    }


    @Override
    public int getItemCount() {
        if (showFooter) {
            return commentList.size() + 1;
        } else {
            return commentList.size();
        }
    }

    /**
     * 下载子评论数据完成
     *
     * @param position
     * @param childComments
     */
    public void loadChildCommentComplete(CommentViewHolder commentViewHolder, int position, List<Comment> childComments) {
        Comment parentComment = commentList.get(position);
        for (Comment childComment : childComments) {
            childComment.setParentComment(parentComment);
        }

        //通过父comment里面的“查看回复”按键的点击事件加载数据展开子评论
        if (commentViewHolder != null) {
            parentComment.addChildCommentList(childComments);
            displayChildComment(commentViewHolder, position, parentComment);
        }//通过最后一个子评论的“加载更多”按键的点击事件加载的子评论
        else {
            displayMoreChildComment(position, childComments, parentComment);

        }
    }

    /**
     * 这个方法是用于 加载更多子评论完成后，展示到界面上
     *
     * @param position
     * @param childComments
     * @param parentComment
     */
    private void displayMoreChildComment(int position, List<Comment> childComments, Comment parentComment) {
        //之前已经展示出来的子评论数量
        int orinalChildSize = parentComment.getChildCommentList().size();
        parentComment.addChildCommentList(childComments);
        //从原来已经展示的子评论后面插入
        commentList.addAll(position + orinalChildSize + 1, childComments);
        notifyItemRangeInserted(position + orinalChildSize + 1, childComments.size());
        //为何这不加1，因为是要让之前的最后一条子评论也刷新，不然会显示“加载更多”的按键，因为它已经不是最后一条了，需要隐藏掉这个按键
        notifyItemRangeChanged(position + orinalChildSize, commentList.size() - 2 - position - orinalChildSize);
    }

    /**
     * 添加子评论完成后，对父评论的子评论size等属性进行设置
     *
     * @param position     父Comment的位置索引
     * @param childComment 子评论
     */
    public void addChildCommentComplete(int position, Comment childComment, RecyclerView.ViewHolder viewHolder) {
        Comment parentComment = commentList.get(position);
        parentComment.addChildComment(childComment);
        childComment.setParentComment(parentComment);
        if (!parentComment.isDisplayChildComments()) {//如果当前父评论不是展开状态，那就显示未展开状态
            parentComment.setDisplayChildComments(true);
            final CommentViewHolder commentViewHolder = (CommentViewHolder) viewHolder;
            commentViewHolder.tv_moreReply.setText("折叠回复：");
            //灰色箭头顺时针旋转90°，
            ViewAnimator.animate(commentViewHolder.iv_arrow).rotation(180).duration(300).onStop(new AnimationListener.Stop() {
                @Override
                public void onStop() {
                    commentViewHolder.iv_arrow.setImageResource(R.drawable.tx_arrow_down_blue);
                }
            }).start();

        }
        commentList.add(position + 1, childComment);
        notifyDataSetChanged();
        setForbiddenItemClick(false);
        //displayChildComment(position, parentComment);
    }


    /**
     * 展示子评论
     *
     * @param position
     * @param parentComment
     */
    private void displayChildComment(final CommentViewHolder commentViewHolder, int position, Comment parentComment) {

        commentViewHolder.tv_moreReply.setText("折叠回复：");
        //灰色箭头顺时针旋转90°，
        ViewAnimator.animate(commentViewHolder.iv_arrow).rotation(180).duration(300).onStop(new AnimationListener.Stop() {
            @Override
            public void onStop() {
                commentViewHolder.iv_arrow.setImageResource(R.drawable.tx_arrow_down_blue);
            }
        }).start();


        parentComment.setDisplayChildComments(true);
        commentList.addAll(position + 1, parentComment.getChildCommentList());
        // notifyDataSetChanged();
        //  notifyItemInserted(position+1);
        int size = parentComment.getChildCommentList().size();
        notifyItemRangeInserted(position + 1, size);
        notifyItemRangeChanged(position + size + 1, commentList.size() - 2 - position - size);


    }

    private void loadChildComment(final CommentAdapter.CommentViewHolder commentViewHolder, final Comment parentComment, final int position) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        Map<String, Object> info = new HashMap<>();
        info.put("parentId", parentComment.getId());
        info.put("page", parentComment.getNextPage() == 0 ? 1 : parentComment.getNextPage());
        info.put("size", 5);
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .getChildComment(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        JSONObject jsonObject = (JSONObject) result.getData();
                        List<Comment> childCommentList = jsonObject.getJSONArray("list").toJavaList(Comment.class);
                        // List<Comment> childCommentList = jsonArray.toJavaList(Comment.class);
                        Boolean hasNextPage = jsonObject.getBoolean("hasNextPage");
                        parentComment.setHaveMoreChildComment(hasNextPage);
                        //保存下一次获取子评论的页码
                        parentComment.setNextPage(jsonObject.getInteger("nextPage"));
                        if (childCommentList.size() != 0) {

                            loadChildCommentComplete(commentViewHolder, position, childCommentList);
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }


    public void showFooter(boolean noMoreData) {
        showFooter = true;
        this.noMoreData = noMoreData;
        //notifyItemInserted(commentList.size());
        notifyDataSetChanged();
    }

    public void hideFooter() {
        showFooter = false;
        notifyItemRemoved(commentList.size());
    }

    public class CommentViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_avatar)
        ImageView iv_avatar;
        @BindView(R.id.tv_nick)
        TextView tv_nick;
        @BindView(R.id.tv_content)
        TextView tv_content;
        @BindView(R.id.rl_show_more_child_comment)
        View rl_showMoreChildComment;
        @BindView(R.id.rl_comment_praise)
        View rl_commentPraise;
        @BindView(R.id.iv_comment_praise)
        ImageView iv_commentPraise;
        @BindView(R.id.tv_comment_praise_size)
        TextView tv_commentPraiseSize;
        @BindView(R.id.tv_child_comment_size)
        TextView tv_childCommentSize;
        @BindView(R.id.tv_more_reply)
        TextView tv_moreReply;
        @BindView(R.id.iv_arrow)
        ImageView iv_arrow;
        @BindView(R.id.rl_comment)
        View rl_comment;

        public CommentViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    class ChildCommentViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_avatar)
        ImageView iv_avatar;
        @BindView(R.id.tv_nick)
        TextView tv_nick;
        @BindView(R.id.tv_content)
        TextView tv_content;
        @BindView(R.id.tv_replay_nick)
        TextView tv_replayNick;
        @BindView(R.id.ll_replay)
        View ll_replay;
        @BindView(R.id.ll_load_more)
        View ll_loadMore;
        @BindView(R.id.line_2)
        View line_2;
        Comment childComment;

        public ChildCommentViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public class FooterViewHolder extends RecyclerView.ViewHolder {

        TextView tvLoadingMsg;
        ProgressBar progressBar;

        FooterViewHolder(View v) {
            super(v);
            initView(v);
        }

        private void initView(View v) {
            progressBar = v.findViewById(R.id.progress_bar);
            tvLoadingMsg = v.findViewById(R.id.tv_loading_msg);
        }
    }

    public void setCommentClickListener(CommentClickListener commentClickListener) {
        this.commentClickListener = commentClickListener;
    }

    /**
     * 为避免在添加子评论的时候，又点击其他 评论item,的加载子评论，导致TopicDetailsActivity中记录的点击点位 失效，最终导致子评论位置错位
     *
     * @param forbiddenItemClick
     */
    public void setForbiddenItemClick(boolean forbiddenItemClick) {
        this.forbiddenItemClick = forbiddenItemClick;
    }

    public interface CommentClickListener {

        void commentItemLongClick(Comment comment);

        /**
         * 用户头像点击，显示用户详情
         *
         * @param targetUser
         */
        void avatarClick(User targetUser);

        /**
         * 普通评论点击事件
         *
         * @param parentComment
         * @param position
         */
        void commentItemClick(Comment parentComment, int position);

        /**
         * 子评论点击事件
         * 对子评论进行回复，为了让该回复显示在某个评论之下，所以仍然把目标评论选为该组子评论的父评论，
         * 和普通评论的区别，需要携带回复对象的User信息，
         *
         * @param parentComment 父评论
         * @param rePlyTarget   回复对象的用户信息
         */
        void childCommentItemClick(Comment parentComment, int position, User rePlyTarget);

        /**
         * 给评论点赞
         *
         * @param targetComment
         * @param position
         */
        void addCommentPraise(Comment targetComment, int position);


        void removeCommentPraise(Comment targetComment, int position);

    }

}
